package leetcode.N101_N200;

import leetcode.comm.ListNode;

import java.util.HashMap;
import java.util.Map;

public class N141 {

    public static void main(String[] args) {
        ListNode l1 = ListNode.generate(1, 2, 4);
        System.out.println(hasCycleByTwoPointer(l1));
        l1.next = l1;
        System.out.println(hasCycleByTwoPointer(l1));
    }

    private static boolean hasCycle(ListNode head) {
        Map<ListNode, Integer> map = new HashMap<>();
        for (ListNode n = head; n != null; n = n.next) {
            if (map.put(n, n.val) != null) {
                return true;
            }
        }
        return false;
    }


    private static boolean hasCycleByTwoPointer(ListNode head) {
        if (head == null) {
            return false;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (true) {
            if (fast == slow) {
                return true;
            }
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
    }
}
